<template>
  <div class="developer-function">
    <a-table
      :expandIcon="expandIcon"
      :rowClassName="rowClassName"
      :columns="columns"
      :data-source="data"
      :rowKey="row=>row.id"
      :indentSize="20"
      :pagination="false"
      :expandIconColumnIndex="1"
      >
      <div slot="type" slot-scope="record">{{record === 1 ? '目录' : record === 2 ? '页面' : record === 3 ? '按钮' : ''}}</div>
      <span slot="name" slot-scope="text, record">
        <a @click="edit(record)">{{text}}</a>
      </span>
      <!-- slot-scope="record" -->
      <div slot="sort" slot-scope="text, record">
        <img class="sort-icon" @click="sort(text, record, 'up')" src="../../assets/img/sort-icon.png"/>
        <img class="sort-icon transform" @click="sort(text, record, 'down')" src="../../assets/img/sort-icon.png"/>
      </div>
      <div slot="status" slot-scope="text, record">
        <a-switch @change="functionUpDownStand(text, record)" checked-children="已上架" un-checked-children="已下架" :checked="text === 1 ? true : false" />
      </div>
      <div slot="action" class="action" slot-scope="text, record">
        <div class="tag" @click="addFunction(record, 1)"><a-icon type="plus" class="icon"/>同级</div>
        <div class="tag" @click="addFunction(record, 2)"><a-icon type="plus" class="icon"/>子级</div>
        <div
          v-if="(record.status !== 1 && data.length > 1) || (record.pid && record.status !== 1)"
          class="tag"
          @click="removeFunction(record)"
        >
          <a-icon type="delete" class="icon"/>删除
        </div>
      </div>
    </a-table>
    <a-modal
      :width="480"
      :confirmLoading="modalLoading"
      v-model="visible"
      :title="modalType === 1 ? '添加模块' : modalType === 2 ? '编辑模块' : ''"
      @ok="handleOk"
      @cancel="cancel"
      okText="确定"
      cancelText="取消"
      :afterClose="()=>this.cancel()"
    >
      <div class="modal" v-if="visible">
        <a-form class="form" :form="form" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }" @submit="handleSubmit">
          <a-form-item label="模块类型：">
            <a-select
              v-decorator="[
                'type',
                { rules: [{ required: true, message: '请选择模块类型!' }] },
              ]"
              placeholder="请选择模块类型!"
              @change="handleSelectChange"
              :disabled="modalType === 2 ? true: false"
            >
              <a-select-option :value="1"
                v-if="(addFunctionData.levelType === 1 && addFunctionData.type ===1) ||
                (addFunctionData.levelType === 1 && addFunctionData.type === 2) ||
                (addFunctionData.levelType === 2 && addFunctionData.type === 1)
                "
              >
                目录
              </a-select-option>
              <a-select-option :value="2"
                v-if="(addFunctionData.levelType === 1 && addFunctionData.type ===1) ||
                (addFunctionData.levelType === 1 && addFunctionData.type === 2) ||
                (addFunctionData.levelType === 2 && addFunctionData.type === 1)
                "
              >
                页面
              </a-select-option>
              <a-select-option :value="3"
                v-if="(addFunctionData.levelType === 1 && addFunctionData.type ===3) ||
                (addFunctionData.levelType === 2 && addFunctionData.type ===2)"
              >
                按钮
              </a-select-option>
              <a-select-option :value="1" v-if="modalType === 2">
                目录
              </a-select-option>
              <a-select-option :value="2" v-if="modalType === 2">
                页面
              </a-select-option>
              <a-select-option :value="3" v-if="modalType === 2">
                按钮
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="模块名称：">
            <a-input
              v-decorator="['name', { rules: [{ required: true, message: '请输入模块名称!' }, {max: 16, message: '请输入不超过16个字符', trigger: 'blur' }] }]"
              placeholder="请输入模块名称!"
            />
          </a-form-item>
          <a-form-item label="模块URL：" v-if="selectType !== 1">
            <a-input
              v-decorator="['url', { rules: [{ required: true, message: '请输入模块URL!' }] }]"
              placeholder="请输入模块URL!"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script>
import {Icon} from 'ant-design-vue';

export default {
  name: 'DeveloperFunction',
  watch: {
    visible() {
      if(!this.visible) {
        this.selectType = '';
      }
    }
  },
  data() {
    return {
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          key: 'index',
          width: '10%'
          // scopedSlots: { customRender: 'index' }
        },
        {
          title: '功能目录',
          dataIndex: 'name',
          key: 'name',
          width: '25%',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '类型',
          dataIndex: 'type',
          key: 'type',
          width: '10%',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '排序',
          dataIndex: 'sort',
          key: 'sort',
          width: '10%',
          scopedSlots: { customRender: 'sort' }
        },
        {
          title: '上下架',
          dataIndex: 'status',
          key: 'status',
          width: '15%',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          width: '25%',
          scopedSlots: { customRender: 'action' }
        }
      ],
      data: [],
      visible: false,
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      addFunctionData: {},
      functionUpDownStandData: {},
      deleteFunctionData: {},
      modalLoading: false,
      modalType: 1,
      sortData: {
        idDown: '',
        idUp: ''
      },
      selectType: ''
    };
  },
  created() {
    this.getFunctionList();
    console.log('$api', this.$api);
  },
  methods: {
    rowClassName(record) {
      if(record.index) {
        return 'bgChange';
      }

      return '';
    },
    // 展开图标
    expandIcon(props) {
      if(props.record.children && props.record.children.length > 0) {
        if (props.expanded) {
          return <a style={{ color: 'black', marginRight: '8px' }} onClick={e => {
            props.onExpand(props.record, e);
          }}><Icon type="down" style={{fontSize: 16}}/></a>;
        } else {
          return <a style={{ color: 'black', marginRight: '8px' }} onClick={e => {
            props.onExpand(props.record, e);
          }}><Icon type="right" style={{fontSize: 16}}/></a>;
        }
      }else{
        return <span style={{marginRight: '8px' }}></span>;
      }
    },
    // 排序
    sort(a, b, type) {
      let list = this.data;
      console.log('排序', a, b, list, type);
      this.listReduce(list, b.id, type);
      console.log('this.sortData', this.sortData);
    },
    listReduce(arr, id, type) {
      arr.forEach((x, index) => {
        if (x.id === id) {
          console.log('x', x, type, index, arr);
          if (type === 'up') {
            console.log('arr[index - 1]', arr[index - 1]);
            if (arr[index - 1]) {
              this.sortData = {
                idDown: x.id,
                idUp: arr[index - 1].id
              };
              this.sortFunction(this.sortData);
            } else {
              this.$message.info('到顶了');
            }
          }
          if (type === 'down') {
            console.log('arr[index + 1]', arr[index + 1]);
            if (arr[index + 1]) {
              this.sortData = {
                idDown: x.id,
                idUp: arr[index + 1].id
              };
              this.sortFunction(this.sortData);
            } else {
              this.$message.info('到底了');
            }

          }
        } else if(x.children && x.children.length) {
          this.listReduce(x.children, id, type);
        }
      });
    },
    // 排序
    sortFunction({idDown, idUp}) {
      console.log(idDown, idUp);
      this.$api.developerFunction.sortFunction({idDown, idUp})
        .then(res => {
          console.log('res', res);
          this.getFunctionList();
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 功能编辑
    edit(record) {
      console.log('record', record);
      this.modalType = 2;
      this.visible = true;
      this.$nextTick(() => {
        this.form.setFieldsValue({
          type: Number(record.type),
          name: record.name,
          url: record.url
        });
        this.selectType = Number(record.type);
      });
      if (this.modalType === 2) {
        this.addFunctionData = {id: record.id};
      }
    },
    getFunctionList() {
      this.$api.developerFunction.getFunctionList()
        .then(res => {
          console.log('res', res);
          let list = res;
          this.data = list.map((item, index) => {
            return {
              ...item,
              index: index < 9 ? `0${index + 1}` : index + 1
            };
          });
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleOk() {
      this.handleSubmit();
    },
    cancel() {
      this.modalLoading = false;
      this.visible = false;
    },
    // 添加功能模块
    addFunction(data, levelType) {
      console.log('添加功能模块', data, levelType);
      if (levelType === 2 && data.type === 3) {
        this.$message.info('按钮不能添加子级');

        return;
      }
      this.visible = true;
      this.modalType = 1;

      this.addFunctionData = {
        currentId: levelType === 1 ? data.id : null,
        pid: levelType === 2 ? data.id : null,
        type: data.type,
        levelType
      };
      console.log('this.addFunctionData', this.addFunctionData);
    },
    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.modalLoading = true;
          console.log('Received values of form: ', values);
          if (this.modalType === 1) {
            this.$api.developerFunction.addFunction({
              ...this.addFunctionData,
              ...values
            })
              .then(res => {
                console.log('res', res);
                this.getFunctionList();
                this.visible = false;
              })
              .catch(() => this.modalLoading = false);
          }
          if (this.modalType === 2) {
            console.log('this.addFunctionData.currentId', this.addFunctionData);
            this.$api.developerFunction.updateFunction({
              id: this.addFunctionData.id,
              name: values.name,
              url: values.url
            })
              .then(res => {
                console.log('res', res);
                this.getFunctionList();
                this.visible = false;
              })
              .catch(() => this.modalLoading = false);
          }

        }
      });
    },
    // 功能上下架
    functionUpDownStand(text, record) {
      console.log('功能上下架', text, record);
      this.functionUpDownStandData = {
        idList: [],
        status: text === 1 ? 0 : text === 0 ? 1 : ''
      };
      // 准备上架
      if (text === 0) {
        console.log('准备上架');
        this.upReduce(record.id, this.data);
        // if (record.children && record.children.length) {
        //   this.downReduce(record.children, 'functionUpDownStandData');
        // }
      }
      // 准备下架
      if (text === 1) {
        if (record.children && record.children.length) {
          console.log(1111);
          this.functionUpDownStandData.idList.push(record.id);
          this.downReduce(record.children, 'functionUpDownStandData');
        } else {
          console.log(22222);
          this.functionUpDownStandData.idList = [record.id];
        }
      }
      console.log('functionUpDownStandData', this.functionUpDownStandData);
      this.$api.developerFunction.functionUpDownStand({...this.functionUpDownStandData})
        .then(res => {
          console.log('res', res);
          this.getFunctionList();
          this.functionUpDownStandData = {};
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 向下递归
    downReduce(arr, funName) {
      console.log('向下递归', arr);
      arr.forEach(element => {
        this[funName].idList.push(element.id);
        if (element.children && element.children.length) {
          this.downReduce(element.children, funName);
        }
      });
    },
    // 向上递归
    upReduce(id, allList) {
      allList.forEach(element => {
        if (element.id === id) {
          console.log('向上递归', element, allList);
          this.functionUpDownStandData.idList.push(element.id);
          this.upReduce(element.pid, this.data);
        } else if(element.children && element.children.length) {
          this.upReduce(id, element.children);
        }
      });
    },
    handleSelectChange(val) {
      this.selectType = val;
    },
    // 删除功能
    removeFunction(data) {
      console.log('删除功能', data);
      let that = this;
      this.deleteFunctionData = {idList: []};
      this.$confirm({
        title: `删除功能模块:${data.name}`,
        content: `您确定要删除${data.name}？模块删除后，连同模块下的子模块都将一并删除。`,
        okText: '确定',
        okType: 'primary',
        cancelText: '取消',
        onOk() {
          console.log('OK');
          if (data.children && data.children.length) {
            that.deleteFunctionData.idList.push(data.id);
            that.downReduce(data.children, 'deleteFunctionData');
          } else {
            that.deleteFunctionData.idList = [data.id];
          }
          console.log('deleteFunctionData', that.deleteFunctionData);
          that.$api.developerFunction.deleteFunction({...that.deleteFunctionData})
            .then(res => {
              console.log('res', res);
              that.getFunctionList();
            })
            .catch(error => {
              console.log(error);
            });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  }
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
/deep/table {
  .bgChange{
    background: #F2F5FA;
    box-shadow: 0px 1px 0px 0px #EEEEEE;
  }
}
.developer-function{
  background: #fff;
  .padding1{
    padding-left: 0px;
  }
  .padding2{
    padding-left: 20px;
  }
  .padding3{
    padding-left: 40px;
  }
  .sort-icon{
    margin-right: 12px;
    width: 16px;
    height: 16px;
    cursor: pointer;
  }
  .transform{
    transform: rotate(180deg);
  }
  .action{
    display: flex;
    padding-right: 50px;
    .tag{
      margin-right: 32px;
      width: 64px;
      height: 24px;
      background: #FFFFFF;
      border: 1px solid rgba(0, 0, 0, 0.15);
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.65);
      text-align: center;
      cursor: pointer;
      border-radius: 2px;
      display: flex;
      align-items: center;
      justify-content: center;
      .icon{
        margin-right: 6px;
      }
    }
  }
}
.modal{
  display: flex;
  justify-content: center;
  .form{
    width: 278px;
    /deep/.ant-form-item-required::before{
      display: none;
    }
  }
}
</style>
